from typing import *
from leetcode.editor.common.node import *


# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        # 维护一个类似 dp[0][(0,len-2):x,[1,len-1]:y]
        # n = len(nums)
        # dp = [{(0, n - 2): (x - nums[n - 1]), (1, n - 1): (x - nums[0])}]
        # if (x - nums[n - 1]) == 0 or (x - nums[0]) == 0:
        #     return 1
        # elif (x - nums[n - 1]) < 0 and (x - nums[0]) < 0:
        #     return -1
        # print(dp)
        # for i in range(1, n):
        #     dp.append({})
        #     count = 2 * (len(dp[i - 1]))  # 有指数此机会
        #     for key, value in dp[i - 1].items():
        #         left, right = key
        #         if left == right:
        #             if value - nums[left] == 0:
        #                 return i+1
        #             else:
        #                 count -= 2
        #                 continue
        #         a = value - nums[left]
        #         if a == 0:
        #             return i + 1
        #         elif a < 0:
        #             count -= 1
        #         else:
        #             dp[i][(left + 1, right)] = a
        #         b = value - nums[right]
        #         if b == 0:
        #             return i + 1
        #         elif b < 0:
        #             count -= 1
        #         else:
        #             dp[i][(left, right - 1)] = b
        #     if count == 0:
        #         return -1


        #---------------------------------------------------------
        #todo第二版
        sumn = sum(nums)
        ll = len(nums)
        left,right = 0,0
        windowsum = 0
        n = -1
        while right < len(nums):
            if windowsum >=0 and sumn - windowsum == x:
                n = n if n != -1 and (ll - (right - left)) > n else (ll - (right - left))
            r = nums[right]
            windowsum += r
            right+=1
            while sumn - windowsum <= x:
                if windowsum >=0 and sumn - windowsum == x:
                    n = n if n != -1 and (ll - (right - left)) > n else (ll - (right - left))
                l = nums[left]
                left +=1
                windowsum -= l
                if left == ll:
                    return n
        return n
# leetcode submit region end(Prohibit modification and deletion)


if __name__ == '__main__':
    solution = Solution()
    print(solution.minOperations(nums=[1,10,1], x=22))
    # your test code here